package com.basic.business.rpaServer;

import com.basic.business.common.constants.Constants;
import com.basic.business.common.enums.PstStatus;
import com.basic.business.common.redis.RedisCacheUtils;
import com.basic.business.common.utils.FileUtils;
import com.basic.business.common.utils.StringUtils;
import com.basic.business.common.utils.kmUtil.KmTagsUtils;
import com.basic.business.log.service.ITOrdersLogService;
import com.basic.business.order.domain.TOrdersDetail;
import com.basic.business.order.domain.TOrdersMain;
import com.basic.business.order.domain.TOrdersStatus;
import com.basic.business.order.service.ITOrdersMainService;
import com.basic.business.order.service.ITOrdersStatusService;
import com.basic.business.redis.domain.TOrdersMainRedis;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 处理文件打包
 *
 * @author zhaoxy_jn@163.com
 */
@Slf4j
@Component
public class HandlePackaging {

    @Resource
    private ITOrdersMainService mainService;

    @Resource
    private ITOrdersStatusService statusService;

    @Resource
    private ITOrdersLogService logService;

    @Resource
    private MultiThreadProcessor threadProcessor;

    @Resource
    private HandlePrint handlePrint;


    /**
     * 打包程序入库
     */
    public void init(TOrdersMain main) {

        // 过滤所有的订单明细状态是WAIT_AUDIT的，且非赠品
        List<TOrdersDetail> detailCollect = main.getDetailList().stream().filter(detail -> StringUtils.equals(detail.getSysStatus(), "WAIT_AUDIT")).filter(detail -> StringUtils.equals(detail.getIsGift(), "N")).collect(Collectors.toList());
        if (!detailCollect.isEmpty()) {
            // 印刷品处理
            boolean isAllPrint = handlePrint.init(detailCollect, main);
            if (isAllPrint) return;
            //非全印刷品处理
            handleNoAllPrints(detailCollect, main);
        }
    }

    /**
     * 非全印刷品处理
     */
    private void handleNoAllPrints(List<TOrdersDetail> detailCollect, TOrdersMain main) {
        // 明细全部满足 26位编码
        boolean isAll26Code = detailCollect.stream().allMatch(detail -> detail.getOuterSkuId().matches("^[0-9a-zA-z]{26}$"));

        if (!isAll26Code) {
            // 非全26位编码 新增正常处理标签，删除不做处理标签，删除印刷品标签，更新Redis自动处理状态为false
            handleNoAll26Code(main);
        } else {
            handleAll26Code(main, detailCollect);
        }
    }

    /**
     * 非全26位编码处理
     */
    private void handleNoAll26Code(TOrdersMain main) {
        long mainSid = main.getSid();

        TOrdersStatus status = TOrdersStatus.createTOrdersStatus(main);

        // 更新标签 新增正常处理标签，删除印刷品标签
        String tagsStr = KmTagsUtils.updateExclusiveTag(mainSid, main.getTags(), KmTagsUtils.TAG_NORMAL_PROCESSING);

        try {
            TOrdersMainRedis mainRedis = RedisCacheUtils.getCacheObject(Constants.ORDERS_REDIS_KEY + mainSid);
            if (mainRedis != null) {
                // 设置Redis中自动处理状态为【人工处理】
                mainRedis.getDetailList().forEach(detail -> detail.setPst(PstStatus.MANUAL.name()));

                // 删除打包文件
                mainRedis.getDetailList().forEach(detail -> {
                    // 获取smb路径
                    String smbPath = detail.getSmbPath();
                    if (StringUtils.isNotBlank(smbPath)) {
                        // 删除打包文件 按逗号分割路径并逐个删除
                        Arrays.stream(smbPath.split(","))
                                .filter(path -> StringUtils.isNotBlank(path.trim()))
                                .forEach(path -> FileUtils.deleteFromSmb(path, main.getShortId()));
                        // 将SMB路径清空
                        detail.setSmbPath(null);
                    }
                });
                if (StringUtils.isNotBlank(tagsStr)) {
                    // 写日志
                    logService.insert(mainSid, mainSid, String.format("执行【非全26编码】策略成功；%s", tagsStr));
                }
                RedisCacheUtils.setCacheObject(Constants.ORDERS_REDIS_KEY + mainSid, mainRedis);
            }

        } catch (Exception e) {
            log.error("执行【非全26编码】策略失败；系统单号：{}；原因：", mainSid, e);
            // 写日志
            logService.insert(mainSid, mainSid, String.format("执行【非全26编码】策略失败；%s", tagsStr));
        } finally {
            // 更新主订单自动处理状态为【人工处理】
            status.setOrderStatus(PstStatus.MANUAL.name());
            statusService.insertPst(status);
        }
    }

    /**
     * 全是26位编码处理
     */
    private void handleAll26Code(TOrdersMain main, List<TOrdersDetail> detailCollect) {
        threadProcessor.init(main, detailCollect);
    }
}
